package wang.kentwang.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import wang.kentwang.beans.User;
import wang.kentwang.dao.Dao;
import wang.kentwang.utils.DBUtil;

public class DaoImpl implements Dao{
	/**
	 * 增加用户
	 */
	public int add(User user) {
		String sql="insert into test(name,phone,age) values(?,?,?)";
		Object[] objs= {user.getName(),user.getPhone(),user.getAge()};
		return DBUtil.cud(sql, objs);
	}
	/**
	 * 根据id删除用户
	 */
	public int delById(int id) {
		String sql="delete from test where id=?";
		Object objs= id;
		return DBUtil.cud(sql, objs);
	}
	/**
	 * 根据id更新User
	 */
	public int updateById(User user) {
		String sql="update test set name=? phone=? age=? where id=?";
		Object[] objs= {user.getName(),user.getPhone(),user.getAge(),user.getId()};
		return DBUtil.cud(sql, objs);
	}
	
	/**
	 * 查询所有用户
	 */
	public List<User> queryAll() {
		List<User> userList=new ArrayList<User>();
		Connection con=DBUtil.getCon();
		PreparedStatement ps=null;
		ResultSet rs =null;
		String sql="select * from test";
		try {
			ps=con.prepareStatement(sql);
			rs =ps.executeQuery();
			while(rs.next()) {
				User user=new User();
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				user.setPhone(rs.getString(3));
				user.setAge(rs.getInt(4));
				//把user放入List集合中
				userList.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userList;
	}
	/**
	 * 根据用户id查询用户
	 */
	public User queryById(int id) {
		Connection con=DBUtil.getCon();
		PreparedStatement ps=null;
		ResultSet rs =null;
		User user=new User();
		String sql="select id,name,phone,age from test where id=?";
		try {
			ps=con.prepareStatement(sql);
			ps.setInt(1, id);
			rs =ps.executeQuery();
			while(rs.next()) {
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				user.setPhone(rs.getString(3));
				user.setAge(rs.getInt(4));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}


}
